package com.atguigu.gmall.product.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.common.cache.GmallCache;
import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.service.RabbitService;
import com.atguigu.gmall.model.product.*;
import com.atguigu.gmall.product.mapper.*;
import com.atguigu.gmall.product.service.ManageService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class ManageServiceImpl implements ManageService {


    @Autowired
    private BaseCategory1Mapper baseCategory1Mapper;
    @Autowired
    private BaseCategory2Mapper baseCategory2Mapper;
    @Autowired
    private BaseCategory3Mapper baseCategory3Mapper;
    @Autowired
    private BaseAttrInfoMapper baseAttrInfoMapper;
    @Autowired
    private BaseAttrValueMapper baseAttrValueMapper;
    @Autowired
    private SpuInfoMapper spuInfoMapper;
    @Autowired
    private BaseSaleAttrMapper baseSaleAttrMapper;
    @Autowired
    private SpuImageMapper spuImageMapper;
    @Autowired
    private SpuPosterMapper spuPosterMapper;
    @Autowired
    private SpuSaleAttrMapper spuSaleAttrMapper;
    @Autowired
    private SpuSaleAttrValueMapper spuSaleAttrValueMapper;
    @Autowired
    private SkuInfoMapper skuInfoMapper;
    @Autowired
    private SkuImageMapper skuImageMapper;
    @Autowired
    private SkuAttrValueMapper skuAttrValueMapper;
    @Autowired
    private SkuSaleAttrValueMapper skuSaleAttrValueMapper;
    @Autowired
    private BaseCategoryViewMapper baseCategoryViewMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private RabbitService rabbitService;

    @Override
    @GmallCache(prefix = "getCategory1:")
    public List<BaseCategory1> getCategory1() {
        return baseCategory1Mapper.selectList(null);
    }

    @Override
    @GmallCache(prefix = "getCategory2:")
    public List<BaseCategory2> getCategory2(Long category1Id) {

        return baseCategory2Mapper.selectList(new QueryWrapper<BaseCategory2>().
                eq("category1_id",category1Id));
    }

    @Override
    @GmallCache(prefix = "getCategory3:")
    public List<BaseCategory3> getCategory3(Long category2Id) {

        return baseCategory3Mapper.selectList(new QueryWrapper<BaseCategory3>().
                eq("category2_id",category2Id));
    }

    @Override
    @GmallCache(prefix = "getAttrInfoList:")
    public List<BaseAttrInfo> getAttrInfoList(Long category1Id, Long category2Id, Long category3Id) {
        //调用mapper
        List<BaseAttrInfo> baseAttrInfoList = baseAttrInfoMapper.selectAttrInfoList(category1Id, category2Id, category3Id);
        return baseAttrInfoList;

    }

    @Override
    @Transactional(rollbackFor = Exception.class) //当发生异常的时候，直接回滚数据
    public void saveAttrInfo(BaseAttrInfo baseAttrInfo) {
        //判断是修改还是新增
        if(baseAttrInfo.getId()!=null){
            //修改
            baseAttrInfoMapper.updateById(baseAttrInfo);
            //修改的时候删除数据 逻辑删除 本质是update
            QueryWrapper<BaseAttrValue> baseAttrValueQueryWrapper = new QueryWrapper<>();
            baseAttrValueQueryWrapper.eq("attr_id",baseAttrInfo.getId());
            baseAttrValueMapper.delete(baseAttrValueQueryWrapper);
        }else{
            //新增
            //保存数据 base_attr_info base_attr_value
            baseAttrInfoMapper.insert(baseAttrInfo);
        }
        //从baseAttrValue.getAttrValueList()
        List<BaseAttrValue> attrValueList = baseAttrInfo.getAttrValueList();
        if (!CollectionUtils.isEmpty(attrValueList)){
            attrValueList.forEach(baseAttrValue -> {
                //attr_id = base_attr_info.id
                baseAttrValue.setAttrId(baseAttrInfo.getId());
                baseAttrValueMapper.insert(baseAttrValue);
            });
        }

    }
    //根据平台属性id回显平台属性值
    @Override
    @GmallCache(prefix = "getAttrValueList:")
    public List<BaseAttrValue> getAttrValueList(Long attrId) {
        QueryWrapper<BaseAttrValue> wrapper = new QueryWrapper<BaseAttrValue>().eq("attr_id", attrId);
        List<BaseAttrValue> baseAttrValueList = baseAttrValueMapper.selectList(wrapper);
        return baseAttrValueList;
    }

    @Override
    @GmallCache(prefix = "getSpuList:")
    public IPage<SpuInfo> getSpuList(Page<SpuInfo> spuInfoPage, SpuInfo spuInfo) {
        QueryWrapper<SpuInfo> spuInfoQueryWrapper = new QueryWrapper<>();
        spuInfoQueryWrapper.eq("category3_id",spuInfo.getCategory3Id());
        spuInfoQueryWrapper.orderByDesc("id");
        return spuInfoMapper.selectPage(spuInfoPage,spuInfoQueryWrapper);
    }
    //获取所有销售属性
    @Override
    @GmallCache(prefix = "getBaseSaleAttrList:")
    public List<BaseSaleAttr> getBaseSaleAttrList() {
        //select * from base_sale_attr where is_delete = 0;
        return baseSaleAttrMapper.selectList(null);
    }

    //保存和修改spu
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveSpuInfo(SpuInfo spuInfo) {
        //判断是修改还是新增
        if (spuInfo.getId()!=null){
            spuInfoMapper.updateById(spuInfo);
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("spu_id",spuInfo.getId());
            spuImageMapper.delete(queryWrapper);
            spuPosterMapper.delete(queryWrapper);
            spuSaleAttrMapper.delete(queryWrapper);
            spuSaleAttrValueMapper.delete(queryWrapper);
        }else {
            spuInfoMapper.insert(spuInfo);
        }
        List<SpuImage> spuImageList = spuInfo.getSpuImageList();
        if (!CollectionUtils.isEmpty(spuImageList)){
            spuImageList.forEach(spuImage -> {
                spuImage.setSpuId(spuInfo.getId());
                spuImageMapper.insert(spuImage);

            });
        }
        List<SpuPoster> spuPosterList = spuInfo.getSpuPosterList();
        if (!CollectionUtils.isEmpty(spuPosterList)){
            spuPosterList.forEach(spuPoster -> {
                spuPoster.setSpuId(spuInfo.getId());
                spuPosterMapper.insert(spuPoster);

            });
        }
        List<SpuSaleAttr> spuSaleAttrList = spuInfo.getSpuSaleAttrList();
        if (!CollectionUtils.isEmpty(spuSaleAttrList)){
            spuSaleAttrList.forEach(spuSaleAttr -> {
                spuSaleAttr.setSpuId(spuInfo.getId());
                spuSaleAttrMapper.insert(spuSaleAttr);


                List<SpuSaleAttrValue> spuSaleAttrValueList = spuSaleAttr.getSpuSaleAttrValueList();
                spuSaleAttrValueList.forEach(spuSaleAttrValue -> {
                    spuSaleAttrValue.setSpuId(spuInfo.getId());
                    spuSaleAttrValue.setSaleAttrName(spuSaleAttr.getSaleAttrName());
                    spuSaleAttrValueMapper.insert(spuSaleAttrValue);
                });
            });
        }

    }

    @Override
    @GmallCache(prefix = "getSpuImageList:")
    public List<SpuImage> getSpuImageList(Long spuId) {
        List<SpuImage> spuImageList = spuImageMapper.selectList(new QueryWrapper<SpuImage>().eq("spu_id", spuId));
        return spuImageList;
    }

    @Override
    @GmallCache(prefix = "getSpuSaleAttrList:")
    public List<SpuSaleAttr> getSpuSaleAttrList(Long spuId) {
        List<SpuSaleAttr> spuSaleAttrList = this.spuSaleAttrMapper.selectSpuSaleAttrList(spuId);
        return spuSaleAttrList;
    }

    //添加sku
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveSkuInfo(SkuInfo skuInfo) {
        //判断是修改还是新增
        if(skuInfo.getId()!=null){
            this.skuInfoMapper.updateById(skuInfo);
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("sku_id",skuInfo.getId());
            skuImageMapper.delete(queryWrapper);
            skuAttrValueMapper.delete(queryWrapper);
            skuSaleAttrValueMapper.delete(queryWrapper);
        }else {
            this.skuInfoMapper.insert(skuInfo);
        }
        List<SkuImage> skuImageList = skuInfo.getSkuImageList();
        if (!CollectionUtils.isEmpty(skuImageList)){
            skuImageList.forEach(skuImage -> {
                skuImage.setSkuId(skuInfo.getId());
                this.skuImageMapper.insert(skuImage);
            });
        }
        List<SkuSaleAttrValue> skuSaleAttrValueList = skuInfo.getSkuSaleAttrValueList();
        if (!CollectionUtils.isEmpty(skuSaleAttrValueList)){
            skuSaleAttrValueList.forEach(skuSaleAttrValue -> {
                skuSaleAttrValue.setSkuId(skuInfo.getId());
                skuSaleAttrValue.setSpuId(skuInfo.getSpuId());
                this.skuSaleAttrValueMapper.insert(skuSaleAttrValue);
            });
        }
        List<SkuAttrValue> skuAttrValueList = skuInfo.getSkuAttrValueList();
        if (!CollectionUtils.isEmpty(skuAttrValueList)){
            skuAttrValueList.forEach(skuAttrValue -> {
                skuAttrValue.setSkuId(skuInfo.getId());
                this.skuAttrValueMapper.insert(skuAttrValue);
            });
        }
        RBloomFilter<Object> bloomFilter = this.redissonClient.getBloomFilter(RedisConst.SKU_BLOOM_FILTER);
        bloomFilter.add(skuInfo.getId());
    }

    //根据三级分类id查询skuInfo列表
    @Override
    @GmallCache(prefix = "getSkuInfoList:")
    public IPage<SkuInfo> getSkuInfoList(Page<SkuInfo> skuInfoPage, SkuInfo skuInfo) {
        QueryWrapper<SkuInfo> skuInfoQueryWrapper = new QueryWrapper<>();
        skuInfoQueryWrapper.eq("category3_id",skuInfo.getCategory3Id());
        skuInfoQueryWrapper.orderByDesc("id");
        return skuInfoMapper.selectPage(skuInfoPage,skuInfoQueryWrapper);
    }

    //上架
    @Override
    public void onSale(Long skuId) {
        SkuInfo skuInfo = new SkuInfo();
        skuInfo.setId(skuId);
        skuInfo.setIsSale(1);
        this.skuInfoMapper.updateById(skuInfo);
        //上架发送消息
        this.rabbitService.sendMsg(MqConst.EXCHANGE_DIRECT_GOODS,MqConst.ROUTING_GOODS_UPPER,skuId);

    }
    //下架
    @Override
    public void cancelSale(Long skuId) {
        SkuInfo skuInfo = new SkuInfo();
        skuInfo.setId(skuId);
        skuInfo.setIsSale(0);
        this.skuInfoMapper.updateById(skuInfo);
        //下架发送消息
        this.rabbitService.sendMsg(MqConst.EXCHANGE_DIRECT_GOODS,MqConst.ROUTING_GOODS_LOWER,skuId);

    }


    /*
    * 根据skuId查询数据回显
    * 查询skuInfo、skuImage、skuAttrValue(sku平台属性值)
    *     skuSaleAttrValue(sku销售属性值)
    * */
    @Override
    @GmallCache(prefix = "getSkuInfo:")
    public SkuInfo getSkuInfo(Long skuId) {
        return getSkuInfoDB(skuId);
        //return getSkuInfoByRedisson(skuId);
    }

    private SkuInfo getSkuInfoByRedisson(Long skuId) {
        //定义一个SkuInfo空对象
        SkuInfo skuInfo = null;
        try {
            String skuKey = RedisConst.SKUKEY_PREFIX+skuId+RedisConst.SKUKEY_SUFFIX;
            skuInfo = (SkuInfo) this.redisTemplate.opsForValue().get(skuKey);
            if (skuInfo==null){
                //加锁
                //定义一个锁的key sku:skuId:lock
                String locKey = RedisConst.SKUKEY_PREFIX+skuId+RedisConst.SKULOCK_SUFFIX;
                //redisson
                RLock lock = this.redissonClient.getLock(locKey);
    //            lock.lock();
    //            业务逻辑
    //            lock.unlock(); 不需要重试机制

                //等待时间 失效时间 时间单位
                boolean result = lock.tryLock(RedisConst.SKULOCK_EXPIRE_PX1, RedisConst.SKULOCK_EXPIRE_PX2, TimeUnit.SECONDS);
                if (result){
                    try {
                        skuInfo = this.getSkuInfoDB(skuId);
                        if (skuInfo==null){
                            SkuInfo skuInfo1 = new SkuInfo();
                            this.redisTemplate.opsForValue().set(skuKey,skuInfo1,RedisConst.SKUKEY_TEMPORARY_TIMEOUT,TimeUnit.SECONDS);
                            return skuInfo1;
                        }
                        this.redisTemplate.opsForValue().set(skuKey,skuInfo,RedisConst.SKUKEY_TIMEOUT,TimeUnit.SECONDS);
                        return skuInfo;
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        lock.unlock();
                    }
                }else{
                    Thread.sleep(500);
                    return getSkuInfoDB(skuId);
                }
            }else{
                return skuInfo;
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return getSkuInfoDB(skuId);
    }

    private SkuInfo getSkuInfoByRedis(Long skuId) {
        //定义一个SkuInfo空对象
        SkuInfo skuInfo = null;
        try {
            String skuKey = RedisConst.SKUKEY_PREFIX+skuId+RedisConst.SKUKEY_SUFFIX;

            skuInfo = (SkuInfo) this.redisTemplate.opsForValue().get(skuKey);

            if (skuInfo==null){
                //加锁
                //定义一个锁的key sku:skuId:lock
                String locKey = RedisConst.SKUKEY_PREFIX+skuId+RedisConst.SKULOCK_SUFFIX;
                //定义一个UUID
                String uuid = UUID.randomUUID().toString();
                //执行上锁方法
                Boolean result = this.redisTemplate.opsForValue().setIfAbsent(locKey, uuid, RedisConst.SKULOCK_EXPIRE_PX2, TimeUnit.SECONDS);
                if (result){
                    skuInfo = this.getSkuInfoDB(skuId);
                    if (skuInfo==null){
                        SkuInfo skuInfo1 = new SkuInfo();
                        this.redisTemplate.opsForValue().set(skuKey,skuInfo1,RedisConst.SKUKEY_TEMPORARY_TIMEOUT,TimeUnit.SECONDS);
                        return skuInfo1;
                    }
                    //将数据放入缓存
                    this.redisTemplate.opsForValue().set(skuKey,skuInfo,RedisConst.SKUKEY_TIMEOUT,TimeUnit.SECONDS);
                    //释放锁
                    String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
                    DefaultRedisScript redisScript = new DefaultRedisScript<>();
                    redisScript.setResultType(Long.class);
                    redisScript.setScriptText(script);
                    this.redisTemplate.execute(redisScript, Arrays.asList(locKey),uuid);
                    return skuInfo;
                }else{
                    try {
                        Thread.sleep(500);
                        return getSkuInfo(skuId);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }else{
                return skuInfo;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //数据库兜底
        return getSkuInfoDB(skuId);
    }




    private SkuInfo getSkuInfoDB(Long skuId) {
        //查询skuInfo
        SkuInfo skuInfo = this.skuInfoMapper.selectById(skuId);
        //查询skuImage
        List<SkuImage> skuImageList = this.skuImageMapper.selectList(new QueryWrapper<SkuImage>().eq("sku_id", skuId));
        skuInfo.setSkuImageList(skuImageList);
        //查询skuAttrValue(sku平台属性值的id)
        List<SkuAttrValue> skuAttrValueList = this.skuAttrValueMapper.selectList(new QueryWrapper<SkuAttrValue>().eq("sku_id", skuId));
        //遍历查询、插入
        skuAttrValueList.forEach(skuAttrValue -> {
            //通过skuAttrValue表中attrId查询baseAttrInfo(平台属性)  attr_id = base_attr_info的id
            BaseAttrInfo baseAttrInfo = baseAttrInfoMapper.selectById(skuAttrValue.getAttrId());
            //通过skuAttrValue表中的valueId查询baseAttrValue(平台属性值)  value_id = base_attr_value的id
            BaseAttrValue baseAttrValue = baseAttrValueMapper.selectById(skuAttrValue.getValueId());

            skuAttrValue.setValueName(baseAttrValue.getValueName());
            skuAttrValue.setAttrName(baseAttrInfo.getAttrName());
        });
        //将skuAttrValueList放入skuInfo
        skuInfo.setSkuAttrValueList(skuAttrValueList);
        //查询SkuSaleAttrValue(sku销售属性值id)
        List<SkuSaleAttrValue> skuSaleAttrValueList = this.skuSaleAttrValueMapper.selectList(new QueryWrapper<SkuSaleAttrValue>().eq("sku_id", skuId));
        //遍历查询、插入
        skuSaleAttrValueList.forEach(skuSaleAttrValue -> {
            //通过skuSaleAttrValue表中的saleAttrValueId查询spuSaleAttrValue(spu销售属性值)
            SpuSaleAttrValue spuSaleAttrValue = this.spuSaleAttrValueMapper.selectById(skuSaleAttrValue.getSaleAttrValueId());
            skuSaleAttrValue.setSaleAttrName(spuSaleAttrValue.getSaleAttrName());
            skuSaleAttrValue.setSaleAttrValueName(spuSaleAttrValue.getSaleAttrValueName());
            skuSaleAttrValue.setBaseSaleAttrId(spuSaleAttrValue.getBaseSaleAttrId());
        });
        skuInfo.setSkuSaleAttrValueList(skuSaleAttrValueList);
        return skuInfo;
    }

    //根据spuId查询数据回显
    @Override
    @GmallCache(prefix = "getSpuInfo:")
    public SpuInfo getSpuInfo(Long spuId) {
        SpuInfo spuInfo = this.spuInfoMapper.selectById(spuId);
        List<SpuImage> spuImageList = this.spuImageMapper.selectList(new QueryWrapper<SpuImage>().eq("spu_id", spuId));
        spuInfo.setSpuImageList(spuImageList);
        List<SpuSaleAttr> spuSaleAttrList = this.spuSaleAttrMapper.selectSpuSaleAttrList(spuId);
        spuInfo.setSpuSaleAttrList(spuSaleAttrList);
        List<SpuPoster> spuPosterList = this.spuPosterMapper.selectList(new QueryWrapper<SpuPoster>().eq("spu_id", spuId));
        spuInfo.setSpuPosterList(spuPosterList);
        return spuInfo;
    }

    ////根据三级分类id获取数据
    @Override
    @GmallCache(prefix = "getCategoryView:")
    public BaseCategoryView getCategoryView(Long category3Id) {
        return baseCategoryViewMapper.selectById(category3Id);
    }

    //查询价格
    @Override
    public BigDecimal getSkuPrice(Long skuId) {
        //SkuInfo skuInfo = skuInfoMapper.selectById(skuId);
        QueryWrapper<SkuInfo> skuInfoQueryWrapper = new QueryWrapper<>();
        skuInfoQueryWrapper.eq("id",skuId);
        skuInfoQueryWrapper.select("price");
        SkuInfo skuInfo = skuInfoMapper.selectOne(skuInfoQueryWrapper);
        if (skuInfo!=null){
            return skuInfo.getPrice();
        }
        //返回价格
        return new BigDecimal("0");
    }

    //根据spuId，skuId 查询销售属性集合
    @Override
    @GmallCache(prefix = "getSpuSaleAttrListCheckBySku:")
    public List<SpuSaleAttr> getSpuSaleAttrListCheckBySku(Long skuId, Long spuId) {
        //调用mapper

        return spuSaleAttrMapper.getSpuSaleAttrListCheckBySku(skuId,spuId);
    }
    //根据spuId获取Map数据集合  map可以代替实体类
    @Override
    @GmallCache(prefix = "getSkuValueIdsMap:")
    public Map getSkuValueIdsMap(Long spuId) {
        HashMap<Object, Object> hashMap = new HashMap<>();
        List<Map> mapList = skuSaleAttrValueMapper.selectSkuValueIdsMap(spuId);
        if (!CollectionUtils.isEmpty(mapList)){
            mapList.forEach(map -> {
                hashMap.put(map.get("value_ids"),map.get("sku_id"));
            });
        }
        return hashMap;
    }

    //根据spuId获取海报信息
    @Override
    @GmallCache(prefix = "poster:")
    public List<SpuPoster> findSpuPosterBySpuId(Long spuId) {
        return spuPosterMapper.selectList(new QueryWrapper<SpuPoster>().eq("spu_id", spuId));
    }

    //根据skuId获取平台属性
    @Override
    @GmallCache(prefix = "attrList")
    public List<BaseAttrInfo> getAttrList(Long skuId) {
        return this.baseAttrInfoMapper.getAttrList(skuId);
    }
    //根据spuId获取skuInfo集合
    @Override
    @GmallCache(prefix = "skuInfoTwo:")
    public List<SkuInfo> getSkuInfoListTwo(Long spuId) {
        QueryWrapper<SkuInfo> skuInfoQueryWrapper = new QueryWrapper<SkuInfo>().eq("spu_id", spuId);
        List<SkuInfo> skuInfoList = this.skuInfoMapper.selectList(skuInfoQueryWrapper);
        return skuInfoList;
    }
    //修改spu附加的修改sku
    @Override
    public void updateSkuInfo(SkuInfo skuInfo) {
        this.skuInfoMapper.updateById(skuInfo);
    }

    @Override
    @GmallCache(prefix = "index:")
    public List<JSONObject> getBaseCategoryList() {
        ArrayList<JSONObject> list = new ArrayList<>();
        /*
        数据结构组装！
           1.先查询所有的分类数据
           2.找出一级分类下二级分类数据
           3.找出二级分类下三级分类数据
         */
        List<BaseCategoryView> baseCategoryViewList = baseCategoryViewMapper.selectList(null);
        //分组去重
        Map<Long, List<BaseCategoryView>> category1Map = baseCategoryViewList.stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory1Id));

        int index = 1;
        //迭代器
        Iterator<Map.Entry<Long, List<BaseCategoryView>>> iterator = category1Map.entrySet().iterator();
        while (iterator.hasNext()){
            JSONObject category1 = new JSONObject();
            Map.Entry<Long, List<BaseCategoryView>> entry = iterator.next();
            Long category1Id = entry.getKey();
            //获取一级分类Id 对应的集合数据
            List<BaseCategoryView> baseCategoryViewList1 = entry.getValue();
            String category1Name = baseCategoryViewList1.get(0).getCategory1Name();
            category1.put("index",index);
            category1.put("categoryId",category1Id);
            category1.put("categoryName",category1Name);

            //index 迭代
            index++;

            List<JSONObject> categoryChildList = new ArrayList<>();
            //获取二级分类数据！
            Map<Long, List<BaseCategoryView>> category2Map = baseCategoryViewList1.stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory2Id));
            Iterator<Map.Entry<Long, List<BaseCategoryView>>> iterator1 = category2Map.entrySet().iterator();
            while (iterator1.hasNext()) {
                //声明一个存储二级分类数据对象
                JSONObject category2 = new JSONObject();
                //获取迭代器数据方法是next()
                Map.Entry<Long, List<BaseCategoryView>> entry1 = iterator1.next();
                Long category2Id = entry1.getKey();
                List<BaseCategoryView> baseCategoryViewList2 = entry1.getValue();
                String category2Name = baseCategoryViewList2.get(0).getCategory2Name();

                category2.put("categoryId",category2Id);
                category2.put("categoryName",category2Name);

                categoryChildList.add(category2);

                List<JSONObject> categoryChild3List = new ArrayList<>();

                baseCategoryViewList2.forEach(baseCategoryView -> {
                    JSONObject category3 = new JSONObject();
                    category3.put("categoryId",baseCategoryView.getCategory3Id());
                    category3.put("categoryName",baseCategoryView.getCategory3Name());
                    categoryChild3List.add(category3);
                });
                //将三级分类集合添加到二级分类数据
                category2.put("categoryChild",categoryChild3List);
            }
            //将二级分类集合添加到一级分类数据
            category1.put("categoryChild",categoryChildList);
            //将一级分类数据添加集合
            list.add(category1);
        }
        return list;
    }


}
